import React, { Component } from 'react'
import {userList} from '../../api/user'
import { Table, Button } from 'antd'
import {formateDate} from "../../utils/dateUtils"

class User extends Component{
  state = {
    users: [], // 所有用户列表
    roles: [], // 所有角色列表
    isShow: false, // 是否显示确认框
  }
  initColumns = () => {
    this.columns = [
      {
        title: '用户名',
        dataIndex: 'username'
      },
      {
        title: '邮箱',
        dataIndex: 'email'
      },

      {
        title: '电话',
        dataIndex: 'phone'
      },
      {
        title: '注册时间',
        dataIndex: 'create_time',
        render: formateDate
      },
      {
        title: '所属角色',
        dataIndex: 'role_id',
        render: (role_id) => this.roleNames[role_id]
      },
      {
        title: '操作',
        render: (user) => (
          <span>
            <Button type="primary" size="small" onClick={() => this.showUpdate(user)}>修改</Button>
            <Button type="primary" size="small" onClick={() => this.deleteUser(user)}>删除</Button>
          </span>
        )
      },
    ]
  }
  getUsers = async() => {
    const result = await userList()
    if(result.status === 0){
      const {users, roles} = result.data
      this.initRoleNames(roles)
      this.setState({
        users,
        roles
      })
    }
  }
  /*
  根据role的数组, 生成包含所有角色名的对象(属性名用角色id值)
   */
  initRoleNames = (roles) => {
    const roleNames = roles.reduce((pre, role) => {
      pre[role._id] = role.name
      return pre
    }, {})
    // 保存
    this.roleNames = roleNames
  }
  componentWillMount () {
    this.initColumns()
  }
  componentDidMount(){
    this.getUsers()
  }
  render() {
    return (
      <div calssName="user">
        <Table bordered rowKey='_id' dataSource={this.state.users} columns={this.columns} />
      </div>
    )
  }
}
export default User